package com.qyer.util.log.util;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;

import org.apache.commons.lang.StringUtils;


public class MyDateUtil 
{
	public static String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
	public static String DATE_FORMAT = "yyyyMMdd";
	public static final String  frm = "dd/MMM/yyyy:HH:mm:ss";
	public static final String  logdateformat ="yyyyMMdd HH:mm:ss";


	
	// 计算起始日期间隔多少天
	public static String getDayInterval(String st, String ed) 
	{
		long day = 0;
		try 
		{
			java.util.Date startDate = DateUtil.parse(st ,logdateformat);
			java.util.Date endDate = DateUtil.parse(ed,logdateformat);
			day = (endDate.getTime() - startDate.getTime()) / (24 * 60 * 60 * 1000);
		} 
		catch (Exception e) 
		{
			return "";
		}
		return day + "";
	}
	public static String getCurDate(String d ,String formatStr){
		
		try {
			
			Date da=new Date(Long.parseLong(d));
			
			return DateUtil.format(da, formatStr);
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}  
	}
	
	/**
	 * 此方法描述的是： 解析 时间
	 * @author: hongxi.sun@qyer.com
	 * @version: 2015年8月29日 下午3:23:38
	 * @return String
	 */
	public static long toTimeStamp(String str) {
		
		
		if (!str.isEmpty()) {
			try {
				String[] tmpstr =str.split(" ");
				if(tmpstr.length>0){
					return DateUtil.parse(tmpstr[0].replace("[", ""),frm).getTime();
				}
			} catch (Exception e) {
				e.printStackTrace();
				return 0;
			}
		}
		return 0;
	}
	
	/**
	 * 此方法描述的是： 解析 时间
	 * @author: hongxi.sun@qyer.com
	 * @version: 2015年8月29日 下午3:23:38
	 * @return String
	 */
	public static String toTimeStamp2(String str) {
		if (!str.isEmpty()) {
			try {
				if(str.length()>0){
					Long res =DateUtil.parse(str,TIME_FORMAT).getTime();
					return res.toString();
				}
			} catch (Exception e) {
				e.printStackTrace();
				return "0";
			}
		}
		return "0";
	}
	public static String getCurDate(String d ){
			
			try {
				Double dd = Double.parseDouble(d);
				
				long l = (long) (dd* 1000);
				
				Date da=new Date(l);
				
				return DateUtil.format(da, logdateformat);
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				return null;
			}  
	}
	
	// 判断起始时间差是否在多少分钟内
	public static boolean getMinitueInterval(String st, String ed, int mins) 
	{
		boolean inMins = false;
		try 
		{
			java.util.Date startDate = DateUtil.parse(st, logdateformat);
			java.util.Date endDate = DateUtil.parse(ed, logdateformat);
			double minitue = (endDate.getTime() * 1.0 - startDate.getTime()) / (60 * 1000);
			System.out.println(minitue);
			if (minitue >= 0 && minitue <= mins) 
			{
				inMins = true;
			} 
			else 
			{
				inMins = false;
			}

		} 
		catch (Exception e) 
		{
			inMins = false;
		}
		return inMins;
	}

	
	
	// 指定日期 N 天以前的日期
	public static String getNDaysAgo(String date, int nDaysAgo) 
	{
		Calendar cal1 = Calendar.getInstance();
		Date dateFormat = null;
		try 
		{
			dateFormat = new SimpleDateFormat(DATE_FORMAT).parse(date);
		} 
		catch (ParseException e) 
		{
			e.printStackTrace();
		}
		Long dateLong = dateFormat.getTime(); // 得到的是 long，类似 date
												// -d"2012-11-12 12:00:00" +%s
		cal1.setTime(new java.util.Date(dateLong));
		cal1.add(Calendar.DATE, -nDaysAgo);
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		return formatter.format(cal1.getTime());
	}

	
	
	// 得到起始范围内的日期列表，包含起始日期，可设置间隔天数
	public static List<String> getDateList(String startDate, String endDate, int intervalDay) 
	{
		List<String> listDate = new ArrayList<String>();

		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		Date dBegin;
		Date dEnd;
		try 
		{
			dBegin = f.parse(startDate);
			dEnd = f.parse(endDate);
			if (dBegin.getTime() <= dEnd.getTime()) 
			{
				for (long i = dBegin.getTime(); i <= dEnd.getTime(); i += 86400000 * (intervalDay + 1)) 
				{
					Date d = new Date(i);
					String date = f.format(d);
					listDate.add(date);
				}
			} 
			else 
			{
				for (long i = dBegin.getTime(); i >= dEnd.getTime(); i -= 86400000 * (intervalDay + 1)) 
				{
					Date d = new Date(i);
					String date = f.format(d);
					listDate.add(date);
				}
			}
		} 
		catch (ParseException e) 
		{
			e.printStackTrace();
		}
		return listDate;
	}

	
	
	// 获取指定日期的前一周（1~7天）时间
	public static List<String> getWeekList(String startDate) 
	{
		List<String> listDate = new ArrayList<String>();

		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		Date dBegin;
		try 
		{
			dBegin = f.parse(startDate);
			for (long i = 1; i <= 7; i++) 
			{
				Date d = new Date(dBegin.getTime() - 86400000 * i);
				String date = f.format(d);
				listDate.add(date);
			}
		} 
		catch (ParseException e) 
		{
			e.printStackTrace();
		}
		return listDate;
	}

	
	
	// 将长整型字符串转换为日期字符串，注意：不能带毫秒
	public static String millis2Time(String longStr) 
	{
		long seconds = Long.parseLong(longStr);
		long millis = seconds * 1000;
		Date date = new Date(millis);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+8"));
		String formattedDate = sdf.format(date);
		return formattedDate;
	}

	
	
	// 将日期字符串转换为长整型数字，注意：输出不带毫秒
	public static long time2Millis(String date) 
	{
		Date dateFormat = null;
		try 
		{
			dateFormat = new SimpleDateFormat(TIME_FORMAT).parse(date);
		} 
		catch (ParseException e) 
		{
			System.out.println(e.toString());
		}
		Long dateLong = dateFormat.getTime(); // 得到的是 long，类似 date
												// -d"2012-11-12 12:00:00" +%s
		return dateLong;
	}

	
	
	// 得到指定日期的星期数，注意：1=星期日 2=星期一 7=星期六，其他类推
	public static String getWeek(String sdate) 
	{
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		ParsePosition pos = new ParsePosition(0);
		Date strtodate = formatter.parse(sdate, pos);
		Calendar c = Calendar.getInstance();
		c.setTime(strtodate);
		// int hour=c.get(Calendar.DAY_OF_WEEK);
		// hour中存的就是星期几了，其范围 1~7
		// 1=星期日 2=星期一 7=星期六，其他类推
		// return new SimpleDateFormat("E").format(c.getTime()); // 返回 星期一
		return String.valueOf(c.get(Calendar.DAY_OF_WEEK));
	}

	
	
	// 得到 1 年以前的日期
	public static String getOneYearsAgo(String dateStr) 
	{
		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		Calendar cal = Calendar.getInstance();
		try 
		{
			cal.setTime(f.parse(dateStr));
		} 
		catch (ParseException e) 
		{
			e.printStackTrace();
		}
		cal.add(Calendar.YEAR, -1);
		Date oneYearsAgo = cal.getTime();
		return f.format(oneYearsAgo);
	}

	
	
	// 得到 N 个月以前的日期
	public static String getNMonthsAgo(String dateStr, int n) 
	{
		SimpleDateFormat f = new SimpleDateFormat("yyyyMMdd");
		Calendar cal = Calendar.getInstance();
		try 
		{
			cal.setTime(f.parse(dateStr));
		} catch (ParseException e) 
		{
			e.printStackTrace();
		}
		cal.add(Calendar.MONTH, 0-n);
		Date nMonthsAgo = cal.getTime();
		return f.format(nMonthsAgo);
	}

	
	
	// 获得上月最后一天的日期
	public static String getPreMonthEnd(String dateStr) 
	{
		String str = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar lastDate = Calendar.getInstance();
		try 
		{
			lastDate.setTime(sdf.parse(dateStr));
		} 
		catch (ParseException e) 
		{
			e.printStackTrace();
		}
		lastDate.add(Calendar.MONTH, -1);// 减一个月
		lastDate.set(Calendar.DATE, 1);// 把日期设置为当月第一天
		lastDate.roll(Calendar.DATE, -1);// 日期回滚一天，也就是本月最后一天
		str = sdf.format(lastDate.getTime());
		return str;
	}

	
	
	// 获得上月最第一天的日期
	public static String getPreMonthFirst(String dateStr) 
	{
		String str = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar lastDate = Calendar.getInstance();
		try 
		{
			lastDate.setTime(sdf.parse(dateStr));
		} 
		catch (ParseException e) 
		{
			e.printStackTrace();
		}
		lastDate.set(Calendar.DATE, 1);// 设为当前月的1号
		lastDate.add(Calendar.MONTH, -1);// 减一个月，变为下月的1号
		str = sdf.format(lastDate.getTime());
		return str;
	}
	public static void main(String[] args) {

		List<String> ss =MyDateUtil.getDateList("20150701", "20150731", 9);
		for(String s :ss){
			System.out.println(s);
		}
		
		String s = StringUtils.replace("{ddd}", "{", "");
		System.out.println(s);
		
		System.out.println(getNDaysAgo("20160701" ,-30));
	}
	
	/**
	  * 得到本周周一
	  * 
	  * @return yyyy-MM-dd
	  */
	 public static String getMondayOfThisWeek() {
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");	 
			 
		  Calendar c = Calendar.getInstance();
		  int day_of_week = c.get(Calendar.DAY_OF_WEEK) - 1;
		  if (day_of_week == 0)
		   day_of_week = 7;
		  c.add(Calendar.DATE, -day_of_week + 1);
		  return sdf.format(c.getTime());
	 }
	 /**
	  * 得到当夜第一天
	  * 
	  * @return yyyy-MM-dd
	  */
	 public static String getFirstDayOfThisMouth() {
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");	 
			 
		  Calendar c = Calendar.getInstance();    
	      c.add(Calendar.MONTH, 0);
	      c.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
	      String first = sdf.format(c.getTime());
	      return first ;
	 }
}